{	    
Indicator:      _FxDeviation.RS

Description:    Plots the deviation of Price relative to reference function, 
                such as: AMA, EMA, Linear Regression curve, Tilson T3 average,
                Jurik moving average, or a constant value.

                Indicator can be smoothed or rounded to nearest tradable value.
                  
                Check formatting Load Additional Data with 1 bar, to ensure Dev calculates immediately
                when RS loads.  If not checked, Dev will calculate when 1st real data tick arrives after
                RS is loaded.
                
Note:			The ROC calculation in this indicator differs from the forumla used in LRDeviation.RS, which 
				compensates for trade direction, and assumes reference point for price will be center line - 2 deviations
				or center line + 2 deviations, depending upon whether anticipated trade is long or short.                

Note:           Format - General Tab - Load additional data must be at least >= Offset specified in input parameters              

Provided By:    MarkSanDiego

Updated:        09/09/08    original version
                12/25/10    StdDevLength and StdErrLength set to LRLength if not specified
                11/28/11    clean up code
                12/16/12    calculating functions without offset provides greater flexibility
				            in using indicator with both historical and real data  
                12/27/12	clarify difference between ROC calculations in this indicator and LRDeviation.RS 
				01/16/13	standardize real time processing
				10/15/15	minor corrections in ROC and gain formulas for consistency with align with LRDeviation.RS indicator
}
  
Input:     
    Price(close), 
    RefPrice(AvgPrice), 
    RefSmooth(0),
    Offset(6),

    RefID(3),                           { reference function identifier }
    AMALength(15),                      { arithmetic moving average length }
    EMALength(15),                      { exponential moving average length }
    LRLength(120),                      { linear regression function length }
    KAMA_EffRatioLen(7),                { Kaufman adaptive moving average parameters }
    KAMA_FastLength(2),                 { Kaufman adaptive moving average parameters }
    KAMA_SlowLength(25),                { Kaufman adaptive moving average parameters }
    T3Length(20),                       { Tilson T3 moving average length }
    JMALength(20),                      { Jurik moving average length }
    JMAPhase(0),                        { Jurik moving average phase parameter }
    __VWAP("No parameter - RefID = 7"),
    RefValue(0),                        { define zero deviation to be this fixed value }

    DevID(2),                           { deviation function identifier }
    StdDevLength(0),                    { standard deviation length }
    StdErrLength(0),                    { standard error length }
    ATRLength(14),                      { average true range length }
    JATRLength(14),                     { percentage }
    Percent(1),                         { points }     
    Pts(1),
    UseAlertColors(true),               { color code deviation from price, according to defined deviation alerts }
    Dev1Alert(1.5),
    Dev2Alert(2.0),
    Dev3Alert(2.5),
    Dev4Alert(3.0),
    DevLevelMin(0),                     { 0 = ignore, otherwise display only DevLevel specified by range DevLevelMin to DevLevelMax  }
    DevLevelMax(0),                     { 0 = ignore, otherwise display only DevLevel specified by range DevLevelMin to DevLevelMax  }
    SwingDevMult(4),                    { Estimated total number of deviation units traversed by successful swing trade }

    int CalcSeconds(15);                { minimum seconds delay between calculations }

Vars: 
    Intrabarpersist Dir(0),				{ Direction of LR slope: 1 = positive, -1 = negative }
    intrabarpersist count(0),           { Calculations count }
    intrabarpersist BS(0),              { Bar Status }    
    intrabarpersist Length(0),
    intrabarpersist YrLength(0),        { LRLength expressed in years }
    intrabarpersist LastBar(false),
    LRTgtBar(-6),                       { linear regression function target bar, always set to negative of offset }
   
    intrabarpersist oRef(0),             { LR Centerline Value1 at End of LR centerline plus Offset bars to right (Current bar) }
    intrabarpersist oRef2(0),            { LRLength Centerline value at end of LR without Offset }
    intrabarpersist oDev(0),             { Value of deviation from LR center line with offset }
    intrabarpersist oDev2(0),            { Value1 of deviation of LR center line without offset }
    intrabarpersist oUnitdev(0),         { Single unit of deviation at Offset Bar }
    intrabarpersist oUnitDev2(0),        { single unit of deviation without offset }
    
    intrabarpersist oLRSlope(0),
    intrabarpersist oLRAngle(0),
    intrabarpersist oLRIntercept(0),
    Intrabarpersist DevLevel(0),
    Intrabarpersist ROC(0),
    intrabarpersist Gain(0),			{ ROC x Length of LR channel }
    intrabarpersist AnnGain(0),         { annualized gain }
    Intrabarpersist RTData(false),      { true, if real time data }
	x(0),
	SwingProfit(0),
    L1(0),                              { adjusted standard deviation length }
    L2(0),                              { adjust standard error length }
    intrabarpersist PlotColor(white),
    intrabarpersist PlotBGColor(black);




var: 
	elsystem.Timer Timer1( NULL ),
	intrabarpersist bool CalcTrigger(false);    { true if calculation should be performed }

Method override void InitializeComponent()
	begin
    	Timer1 = new elsystem.Timer;
    	Timer1.Interval = CalcSeconds * 1000;
    	Timer1.AutoReset = true;
    	Timer1.Enable = true;
    	Timer1.Name = "Timer1";
    	Timer1.elapsed += Timer1_Elapsed;  
	end;
 
{ run once every CalcSeconds seconds}
{The Elapsed event handler is called when the timer counts down to zero}
Method void Timer1_Elapsed( elsystem.Object sender, elsystem.TimerElapsedEventArgs args ) 
	begin 
    	 //BS = -1;            { all timer generated executions associated with BarStatus(1) = -1 (undefined) }
    	CalcTrigger = true;        
	end;


{
Method  :       _FxDeviationMethod() 

Description:    This method calculates the unit deviation from a defined reference.

                In general, this method should be called only during BarStatus(1) = 2 conditions
                as the result values only change once per bar

Provided By:    Mark J. Krisburg

Modified:       12/16/11    original version
                

RefID:          (0) RefPrice (input RefPrice without averaging )
                (1) Simple Moving Average 
                (2) Exponential Moving Average 
                (3) Linear Regression 
                (4) T3 Average
                (5) Jurik Moving Average
                (6) Reference Value 

DevID:          (0) Raw deviation without further processing 
                (1) Standard Deviations ( Param=SDLength )
                (2) Standard Error ( Parm = SELength )
                (3) AvgTrueRange ( Param=ATRLength )
                (4) JMA True Range ( ATR using Juric moving average )
                (5) Percent
                (6) Points

}
          
Method void FxDeviation()
begin    
    
    Once Begin		{ determine Length in use }	
    
    	Switch RefID begin
         	Case 1:
	            Length = AMALength;
        	Case 2:
	            Length = EMALength;
        	Case 3:
	            Length = LRLength;           
         	Case 5:
	            Length = T3Length;
        	
        	{ uncomment the next two lines if you have purchased Jurik Moving Average functions }
	//        Case 6:    
	//            Length = JMALength;
     	end;

		{ Length expressed in terms of years }
        YrLength = (DateToJulian(Date) - DateToJulian(Date[Length]))/365;

        switch DevID begin
             Case 1:
                L1 = MaxList(2, iff(StdDevLength > 0, StdDevLength, Length));     { StdDev Length must be >= 2 }
            Case 2:
                L2 = MaxList(3, iff(StdErrLength > 0, StdErrLength, Length));     { StdErr Length must be >= 3 }
         end;    
    	
	end;    	
    
    
    switch RefID begin  
        Case 0:
            oRef = RefPrice[Offset];
        Case 1:
            oRef = AverageFC(RefPrice[Offset], AMALength);
        Case 2:
            oRef = _XAverage.Simple(RefPrice[Offset], EMALength);
        Case 3:
            Value1 = _LinearRegFaster( RefPrice[Offset], LRLength, LRTgtBar, oLRSlope, oLRAngle, oLRIntercept, oRef) ; { LRTgrBar = -Offset }     
        
        Case 4:
            oRef = AdaptiveMovAvg(RefPrice[Offset],  KAMA_EffRatioLen, KAMA_FastLength, KAMA_SlowLength);
        Case 5:
            oRef = T3Average.series(RefPrice[Offset], T3Length);
        
//       uncomment the next two lines if you have purchased Jurik Moving Average functions
//        Case 6:    
//            oRef = JRC.JMA.2K(RefPrice[Offset], JMALength, JMAPhase);
        Case 7:
            oRef = _VWAP[Offset];
        Case 8:
            oRef = RefValue;
    end;

 
    switch DevID begin
        Case 0:                    
            oUnitDev = 1;            { raw deviation without processing }
        Case 1:
            oUnitDev = _StdDev(RefPrice[Offset], L1);
        Case 2:
            oUnitDev = _StdError(RefPrice[Offset], L2);
        Case 3:
            oUnitDev2 = _AvgTrueRange(ATRLength);
            oUnitdev = oUnitDev2[Offset];
        
//        uncomment the next two lines if you have purchased Jurik Moving Average functions
//        case 4:
//            oUnitDev2 = _JMATrueRange(JATRLength);
        Case 5:
            oUnitDev = RefPrice[Offset] * Percent / 100; 
        Case 6:
            oUnitDev = Pts;
    end;
 
 end;   


Method void EOBCalc()
	begin
			
	    { unit deviation and slope values calculated at the offset bar, where they will NOT be influenced by the most recent Offset bars }
        { price deviation is calculated with LR centerline projected right to current bar }
	        oRef2 = oLRIntercept + oLRSlope * (Length - 1);
       							
        { calculate deviation and direction of trend at current bar, not offset bar }
        if oUnitDev <> 0 then oDev = (Price - oRef)/oUnitDev;
        Dir = sign(oLRSlope);

        { calculate swing component of profit, risk and ROC for long and short trades }       
        x = oUnitdev * SwingDevMult / 2;
     
		Switch Dir begin
			        
            Case 1:   { long }
                SwingProfit = (oRef + x ) / (oRef - x) - 1;
                 if (oRef - x) <> 0 then ROC = oLRSlope / (oRef - x);
                if oLRIntercept <> 0 then Gain = (oRef2/oLRIntercept - 1) * Dir;
                              
            Case -1:  { Short }   
                SwingProfit = 1 - (oRef - x ) / (oRef + x);            
                if (oRef + x) <> 0 then ROC = oLRSlope / (oRef + x);
                If oLRIntercept <> 0 then Gain = (1 - oRef2/oLRIntercept) * Dir;  
		                                
		end;

        AnnGain = Gain / YrLength;
	       					
	end;
			

Method void TrigCalc()
    begin
    
    { Calculations triggered by timer }
    
        Count = Count + 1;
        
        { calculate each tick }
        if oUnitDev <> 0 then oDev = (Price - oRef)/oUnitDev;
        
        { alerts }
        If UseAlertColors then begin
        
            switch oDev begin
                        
                case >= Dev4Alert:
                    DevLevel = 4;
                    PlotColor = black;
                    PlotBGColor = green;            
                Case >= Dev3Alert:
                    DevLevel = 3;
                    PlotColor = green;    
                    PlotBGColor = black;        
                Case >= Dev2Alert:
                    DevLevel = 2;
                    PlotColor = black;
                    PlotBGColor = red;            
                Case >= Dev1Alert:
                    DevLevel = 1;
                    PlotColor = red;
                    PlotBGColor = black;    
                                    
                Case <= - Dev4Alert:
                    DevLevel = -4;
                    PlotColor = black;
                    PlotBGColor = red;
                Case <= -Dev3Alert:
                    DevLevel = -3;
                    PlotColor = red;
                    PlotBGColor = black;
                Case <= -Dev2Alert:
                    DevLevel = -2;
                    PlotColor = black;
                    PlotBGColor = green;
                Case <= -Dev1Alert:
                    DevLevel = -1;
                    PlotColor = green;
                    PlotBGColor = black;
                                                                                                                                    
                Default:
                    DevLevel = 0;
                    PlotColor = lightgray; 
                    PlotBGColor = black;                                                         
        
            end;
                    
        end;            
    
    end;        { Method Calculations }


Method void Plotter()
    begin
        
        plot1(Length, "Len", yellow);
        plot2(Offset, "xOff");
        plot3(-Offset, "Tgt");
        plot4(oDev,"Dev");
        plot5(ROC, "ROC");
        plot6(Gain, "Gain");
        plot7(AnnGain, "Ann Gain");        
         
 {}        
        { debug - may comment these out, or hide outputs using indicator Formatting }
        plot18(oRef, "oRef");
        plot19(oUnitDev, "UnitDev");       
        plot24(Date[Offset], "Date[xOff]");
        plot25(Price, "Price");    
        plot26(CalcSeconds, "Calc Sec");    
        plot27(count, "Count");        
        plot28(BS, "BS");         
         
         
        SetPlotBGColor(1, blue);       
        SetPlotColor(4, PlotColor);
        SetPlotBGColor(4, PlotBGColor);
        
    end;    { Method Plotter }




#region Main Program
    
    #region Tick Processing
        BS = BarStatus(1);
    #endregion	{ Tick Processing }	   
      
        Switch BS begin       
        	
        	Case 1:
        
	        	#region Intrabar Processing	
	        	
	        		#region Triggered Calculations
			    
            			{ Calculate immediately at start of real time data } 
            			once begin
            			
            				CalcTrigger = true;      
            				FxDeviation();
            				EOBCalc();
       						
						end;            				
			
            			{ Calculations once every CalcSeconds during real time data }
            			If CalcTrigger then begin  
	                		TrigCalc(); 
                			CalcTrigger = false;       
            			end;   
			        
        			#endregion;     
			         
         			
        			#region Plotting
        			             		
            			If (DevLevelMin = 0 and DevLevelMax = 0) OR (oDev >= DevLevelMin AND oDev <= DevLevelMax) then begin    
			                Plotter();        
            			end;	
            			        	
        			#endregion
        
				#endregion 		{ Intrabar Processing }
			
    		
			Case 2:

    			#region EndOfBar Processing		

            		FxDeviation();
            		EOBCalc();

            		TrigCalc();
            		If (DevLevelMin = 0 and DevLevelMax = 0) OR (oDev >= DevLevelMin AND oDev <= DevLevelMax) then begin    
	           			Plotter();        
            		end;
  
    			#endregion		{ EndOfBar Processing }                            
            
        end;
                         
#endregion		{ Main Program }

